#include <iostream>
#include <map>
using namespace std;

typedef unsigned int uint;
typedef map <uint, uint> Map;
typedef Map::iterator It;


int main ()
{
	uint z, i, m, l, step, t = 0;
	It it;

	while (cin >> z >> i >> m >> l, (z || i || m || l))
	{
		Map seq;
		++t;
		seq[l] = 0;
		step = 1;
		while (true)
		{
			l = (z * l + i) % m;
			it = seq.find (l);
			if (it != seq.end())
				break;
			seq[l] = step;
			++step;
		}

		cout << "Case " << t << ": " << (step - seq[l]) << '\n';
	}

	return 0;
}